package src.Fifteen;

import javax.swing.*;

public class Commnicate extends JFrame {

    private Thread t1;
    private Thread t2;
    private int count = 0;

    private JProgressBar progressBar;

    public static void main(String[] args) {
        init(new Commnicate(),500,500);
    }

    public static void init(JFrame jFrame,int weight,int height){
        jFrame.setSize(weight,height);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public Commnicate(){
        progressBar = new JProgressBar();
        progressBar.setSize(100,20);
        progressBar.setStringPainted(true);
        getContentPane().add(progressBar);
        delValue();
        addValue();
        t2.start();
        t1.start();

    }

    public void addValue(){
        t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if(count == 101){
                        synchronized (t2){
                            t2.notify();
                        }
                        try {
                            synchronized (t1){
                                t1.wait();
                            }

                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    progressBar.setValue(++count);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }

            }
        });
    }

    public void delValue(){
        t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                while (true){
                    if(count==0){
                        synchronized (t1){
                            t1.notify();
                        }
                        synchronized (t2){
                            try {
                                t2.wait();
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }

                    }
                    progressBar.setValue(--count);
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            }
        });
    }
}
